package my.hospital.servlet;

import my.hospital.util.DBConnection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * Servlet implementation class FetchDataServlet
 */
public class FetchDataServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FetchDataServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<String[]> records = new ArrayList<>();
        try (Connection conn = DBConnection.getConnection()) {
            System.out.println("Database connection established.");
            Statement stmt = conn.createStatement();
            String sql = "SELECT idNumber, name, birthdate, phoneNumber, region, address FROM registration_info";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                String[] record = {
                    rs.getString("idNumber"),
                    rs.getString("name"),
                    rs.getString("birthdate"),
                    rs.getString("phoneNumber"),
                    rs.getString("region"),
                    rs.getString("address")
                };
                records.add(record);
            }
            System.out.println("Data retrieval successful. Number of records: " + records.size());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.setAttribute("records", records);
        request.getRequestDispatcher("DisplayData.jsp").forward(request, response);
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
